package com.hqyj.am.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hqyj.am.pojo.ResultVo;
import com.hqyj.am.service.SmsService;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: chenglongfei
 * @date: 2022/8/17
 * @Description SmsServiceImpl
 */
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    //注入短信发送对
    @Autowired
    SmsClient smsClient;

    @Override
    public ResultVo smsSend(String phone) {
        ResultVo rv =new ResultVo();
        //创建短信发送对象
        SendSmsRequest request = new SendSmsRequest();
        //定义发送的电话参数
        String p[] = {phone};
        request.setPhoneNumberSet(p);
        //定义发送的短信sdk
        request.setSmsSdkAppId("1400716950");
        //定义发送的短信模块Id
        request.setTemplateId("1499373");
        //定义发送的短信签名
        request.setSignName("程龙飞新注册公众号");
        //定义发送的验证码
        Random rd= new Random();
        String code= rd.nextInt(10000)+"";
        String[] d={code};
        request.setTemplateParamSet(d);
        //发送短信。获取
        SendSmsResponse rs  = null;
        try {
            rs = smsClient.SendSms(request);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            rv.setInfo("短信发送失败");
        }
        System.out.println(SendSmsResponse.toJsonString(rs));
        //把响应结果转换成java对象
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            HashMap<String,Object> map = (HashMap<String, Object>) objectMapper.readValue(SendSmsResponse.toJsonString(rs), Map.class);
            ArrayList<LinkedHashMap<String,Object>> list =( ArrayList<LinkedHashMap<String,Object>> ) map.get("SendStatusSet");
            if(list.get(0).get("Code").equals("Ok")){
                //存入验证码到redis缓存中,存入缓存一分钟
                redisTemplate.opsForValue().set("code:"+phone,code,1, TimeUnit.MINUTES);
                rv.setInfo("短信发送成功");
                rv.setSuccess(true);
            }else{
                rv.setInfo("短信发送失败");
            }

        } catch (JsonProcessingException e) {
            e.printStackTrace();
            rv.setInfo("短信发送失败");
        }

        return rv;
    }
}
